package cn.com.youjile.service;

import cn.com.youjile.entity.MsgInfo;
import cn.com.youjile.observer.MsgObserver;
import cn.com.youjile.observer.MsgSubject;
import cn.com.youjile.utils.MsgNumUtil;
import cn.com.youjile.utils.ResultUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe 客户端退出
 */
@Slf4j
@Service
public class ClientExit extends MsgObserver {

    public ClientExit(){
        MsgSubject.getInstance().attach(this);
    }

    @Override
    public void update(ChannelHandlerContext ctx, MsgInfo msg) {
        if(msg.getCode() == MsgNumUtil.s_client_exit) {
            log.info("server [" + MsgNumUtil.s_client_exit + "] 客户端退出:ctx = [" + ctx + "], msg = [" + msg + "]");
            Channel channel = ctx.channel();
            log.info("server [" + MsgNumUtil.s_client_exit + "] 客户端退出:关闭连接 " + channel.remoteAddress());
            byte[] success = ResultUtil.success();
            msg.setInfo(success);
            msg.setCode(MsgNumUtil.success);
            ctx.writeAndFlush(msg);
            channel.close();
            ctx.close();
        }
    }
}
